import logging
from dtos.result import Result
from utils.common_util import CommonUtil


class FormDataParamsUtil(object):
    def __init__(self, params):
        self.params = params

    def check(self, params_list):
        res, sign_res = {}, {}
        for param_item in params_list:
            param, is_required, default_value = param_item

            param_res = self.params.get(param, None)
            if param_res or param_res == 0:
                sign_res[param] = CommonUtil.bytes_str(param_res[0])
            else:
                param_res = default_value
            if not param_res and is_required:
                return Result.error_result(message="form-data中缺少参数：%s" % str(param))
            try:
                if param_res or param_res == 0:
                    if isinstance(param_res, list):
                        res[param] = CommonUtil.bytes_str(param_res[0])
                    else:
                        res[param] = param_res
                else:
                    res[param] = None
            except Exception as ex:
                logging.info("字节类型转换为字符串时出现异常，原因：%s" % str(ex))
                return Result.error_result(message="form-data中参数错误：%s" % str(param))
        return Result.success_result(data={
            "res": res,
            "sign_res": sign_res
        })
